<?php
/**
 * Date: 2017/12/29
 * Time: 16:32
 */

namespace app\admin\controller;

use app\admin\model\Admin;
use app\common\library\Hash;
use think\facade\Request;
use think\Validate;
use think\facade\Cache;
use think\Db;
use Endroid\QrCode\ErrorCorrectionLevel;
use Endroid\QrCode\LabelAlignment;
use Endroid\QrCode\QrCode;

class Work extends Base
{
    public function qrcode()
    {
        $info = Request::header();
        // dump($info);
        $str = md5($info['accept'] . $info['accept-encoding'] . $info['user-agent'] . Request::ip() . session_id() . Request::host());
        //dump($info['accept'] . $info['accept-encoding'] . $info['user-agent'] . Request::ip().session_id().Request::host());
        //dump($str);
        Cache::remember('login' . $str, function () {
            return 'login';
        });
        if (cache('login' . $str) == 'login') {

            if (cache('login' . $str . 'time') > time()) {
                $qrcode = cache('login' . $str . 'qrcode');
            } else {
                cache('login' . $str . 'time', time() + 60 * 2);
                $url = url('/wx/work/login?token=' . $str);
                $qrcode = $this->phpqrcode($url);
                cache('login' . $str . 'qrcode', $qrcode, time() + 60 * 2.5);
            }
            $this->error('获取二维码成功' , $qrcode);//二维码
        } else {
            $admin = Admin::get(['username' => cache('login' . $str)]);
            // dump($admin);
            if (!$admin) {
                $this->error('扫码信息错误');
            } else {
                if (1 != $admin['status']) {
                    $this->error('该用户已被禁用，无法登陆');
                } else {
                    //登录成功
                    $admin['login_times'] = $admin['login_times'] + 1;
                    $admin['last_login_ip'] = Request::ip();
                    $admin['last_login_time'] = time();
                    $admin['token'] = md5($admin['username'] . $admin['password'] . uniqid());
                    if ($admin->save() && app()->rbac->login($admin)) {
                        cookie('username', $admin['username']);
                        session('uid', $admin['id']);
                        $group_id = Db::name('auth_group_access')->where('uid', $admin['id'])->value('group_id');
                        session('group_id', $group_id);
                        cache('login' . $str, null);
                        $sdata['url'] = url('index/index');
                    }
                    $this->success('登录成功');
                }
            }
        }
    }

    //生成二维码
    public function phpqrcode($url)
    {
        $file_name = 'qrcode';
        $qrCode = new QrCode();
        $qrCode->setText('https://' . Request::host() . '/' . $url);
        $qrCode->setSize(250);
        $qrCode->setForegroundColor(array('r' => 0, 'g' => 0, 'b' => 0, 'a' => 0));
        $qrCode->setBackgroundColor(array('r' => 255, 'g' => 255, 'b' => 255, 'a' => 0));
        $qrCode->setLabelFontSize(16);
        //ob_clean();
        //header('Content-Type: ' . $qrCode->getContentType());

        $file_path = $file_name . '/qrcode' . uniqid() . '.png';
        if (!file_exists($file_name)) {
            mkdir($file_name, 0777, true);
        }
        try {
            $qrCode->writeFile($file_path);
            //echo $file_path;
            return $file_path;
        } catch (\Exception $e) {
            return false;
        }

    }

    /**
     * @return object
     */
    public function login()
    {


        if ($this->request->isPost()) {
            $post = $this->request->only(['username', 'password', 'captcha'], 'post');
            $validate = Validate::make([
                'username|登录名' => 'require|max:32',
                'password|密码' => 'require|length:6,16',
                'captcha|验证码' => 'require|captcha',
            ]);
            if (!$validate->check($post)) {
                $this->error($validate->getError());
            }

            $admin = Admin::get(['username' => $post['username']]);
            if (!$admin) {
                $this->error('登录名不存在');
            }
            if (!Hash::check($post['password'], $admin['password'])) {
                $this->error('密码错误');
            }
            if (1 != $admin['status']) {
                $this->error('该用户已被禁用，无法登陆');
            }

            //登录成功
            $admin['login_times'] = $admin['login_times'] + 1;
            $admin['last_login_ip'] = Request::ip();
            $admin['last_login_time'] = time();
            $admin['token'] = md5($admin['username'] . $admin['password'] . uniqid());
            if ($admin->save() && app()->rbac->login($admin)) {
                cookie('username', $admin['username']);
                session('uid', $admin['id']);
                $group_id = Db::name('auth_group_access')->where('uid', $admin['id'])->value('group_id');
                session('group_id', $group_id);
                $this->success('登录成功', 'index/index');
            }
            $this->error('登录失败');
        } else {

            if (cache('update_cache_time') == 1) {

            } else {
                Cache::clear();
                cache('update_cache_time', 1, 3600);
            }
            if (app()->rbac->user()) {
                return redirect(url('/'));
            }
            return view();
        }
    }

    public function logout()
    {
        app()->rbac->logout();
        return redirect('login');
    }
}